<template>
  <view class="order-detail">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-info">
        <text class="status-text">{{ statusText }}</text>
        <text class="status-desc">{{ statusDesc }}</text>
      </view>
      <image class="status-image" :src="statusImage" mode="aspectFit"></image>
    </view>
    
    <!-- 收货地址 -->
    <view class="address-section">
      <view class="address-title">
        <text class="icon">📍</text>
        <text class="title">收货地址</text>
      </view>
      <view class="address-content">
        <view class="user-info">
          <text class="name">{{ order.address.name }}</text>
          <text class="phone">{{ order.address.phone }}</text>
        </view>
        <view class="address-detail">{{ fullAddress }}</view>
      </view>
    </view>
    
    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">订单信息</view>
      <view class="info-item">
        <text class="label">订单编号</text>
        <view class="value-copy">
          <text class="value">{{ order.id }}</text>
          <text class="copy-btn" @click="copyOrderId">复制</text>
        </view>
      </view>
      <view class="info-item">
        <text class="label">创建时间</text>
        <text class="value">{{ order.createTime }}</text>
      </view>
      <view class="info-item" v-if="order.payTime">
        <text class="label">支付时间</text>
        <text class="value">{{ order.payTime }}</text>
      </view>
      <view class="info-item" v-if="order.deliveryTime">
        <text class="label">发货时间</text>
        <text class="value">{{ order.deliveryTime }}</text>
      </view>
      <view class="info-item" v-if="order.completeTime">
        <text class="label">完成时间</text>
        <text class="value">{{ order.completeTime }}</text>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <view class="products-section">
      <view class="section-title">商品信息</view>
      <view 
        class="product-item" 
        v-for="(product, index) in order.products" 
        :key="index"
        @click="goToProductDetail(product.id)"
      >
        <image class="product-image" :src="product.image" mode="aspectFill"></image>
        <view class="product-info">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-spec">{{ product.specificationName }}</view>
          <view class="product-price-info">
            <text class="price">{{ product.price.toFixed(2) }}</text>
            <text class="quantity">x{{ product.count }}</text>
          </view>
        </view>
      </view>
      <view class="amount-info">
        <view class="amount-item">
          <text>商品总额</text>
          <text>{{ order.totalAmount.toFixed(2) }}</text>
        </view>
        <view class="amount-item">
          <text>运费</text>
          <text>+0.00</text>
        </view>
        <view class="amount-item total">
          <text>实付款</text>
          <text class="total-amount">{{ order.totalAmount.toFixed(2) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-bar">
      <view class="action-btn plain" v-if="order.status === 1" @click="cancelOrder">取消订单</view>
      <view class="action-btn primary" v-if="order.status === 1" @click="payOrder">立即支付</view>
      <view class="action-btn plain" v-if="order.status === 3" @click="viewLogistics">查看物流</view>
      <view class="action-btn primary" v-if="order.status === 3" @click="confirmReceive">确认收货</view>
      <view class="action-btn plain" v-if="order.status === 4" @click="deleteOrder">删除订单</view>
      <view class="action-btn primary" v-if="order.status === 4" @click="buyAgain">再次购买</view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex';
import orderApi from '@/api/order.js';
import '@/styles/pages/order/detail.scss';

export default {
  data() {
    return {
      id: '',
      order: {
        id: '',
        userId: '',
        products: [],
        totalAmount: 0,
        status: 0,
        address: {
          name: '',
          phone: '',
          province: '',
          city: '',
          district: '',
          address: ''
        },
        createTime: '',
        payTime: null,
        deliveryTime: null,
        completeTime: null
      }
    };
  },
  computed: {
    statusText() {
      const statusMap = {
        1: '待付款',
        2: '待发货',
        3: '待收货',
        4: '已完成',
        5: '已取消'
      };
      return statusMap[this.order.status] || '未知状态';
    },
    statusDesc() {
      const descMap = {
        1: '请在24小时内完成支付，否则订单将自动取消',
        2: '商家正在处理您的订单，请耐心等待',
        3: '商品已发出，请注意查收',
        4: '订单已完成，感谢您的购买',
        5: '订单已取消'
      };
      return descMap[this.order.status] || '';
    },
    statusImage() {
      const imageMap = {
        1: '/static/images/icons/order-wait-pay.png',
        2: '/static/images/icons/order-wait-ship.png',
        3: '/static/images/icons/order-wait-receive.png',
        4: '/static/images/icons/order-completed.png',
        5: '/static/images/icons/order-canceled.png'
      };
      return imageMap[this.order.status] || '';
    },
    fullAddress() {
      const { province, city, district, address } = this.order.address;
      return province + city + district + address;
    }
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id;
      this.getOrderDetail();
    }
  },
  methods: {
    ...mapActions('order', [
      'updateCurrentOrder'
    ]),
    
    // 获取订单详情
    async getOrderDetail() {
      uni.showLoading({
        title: '加载中'
      });
      
      try {
        const res = await orderApi.getOrderDetail(this.id);
        this.order = res;
        
        // 更新Vuex中的当前订单
        this.updateCurrentOrder(res);
        
        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '获取订单详情失败',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    
    // 复制订单号
    copyOrderId() {
      uni.setClipboardData({
        data: this.order.id,
        success: () => {
          uni.showToast({
            title: '复制成功',
            icon: 'success'
          });
        }
      });
    },
    
    // 取消订单
    async cancelOrder() {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '取消中...' });
              await orderApi.cancelOrder(this.id);
              
              // 刷新订单详情
              await this.getOrderDetail();
              
              uni.hideLoading();
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              });
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '取消订单失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 支付订单
    async payOrder() {
      try {
        uni.showLoading({ title: '准备支付...' });
        await orderApi.payOrder(this.id);
        
        // 刷新订单详情
        await this.getOrderDetail();
        
        uni.hideLoading();
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        });
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '支付失败',
          icon: 'none'
        });
      }
    },
    
    // 查看物流
    viewLogistics() {
      uni.navigateTo({
        url: `/pages/order/logistics?id=${this.id}`
      });
    },
    
    // 确认收货
    async confirmReceive() {
      uni.showModal({
        title: '提示',
        content: '确认已收到商品吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' });
              await orderApi.confirmOrder(this.id);
              
              // 刷新订单详情
              await this.getOrderDetail();
              
              uni.hideLoading();
              uni.showToast({
                title: '确认收货成功',
                icon: 'success'
              });
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '确认收货失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 删除订单
    async deleteOrder() {
      uni.showModal({
        title: '提示',
        content: '确定要删除该订单吗？删除后将无法恢复',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' });
              await orderApi.deleteOrder(this.id);
              
              uni.hideLoading();
              uni.showToast({
                title: '订单已删除',
                icon: 'success'
              });
              
              // 返回上一页
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '删除订单失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 再次购买
    buyAgain() {
      // 将商品添加到购物车
      uni.showLoading({ title: '处理中...' });
      
      // 模拟添加到购物车
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '已添加到购物车',
          icon: 'success'
        });
        
        // 跳转到购物车页面
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/cart/cart'
          });
        }, 1500);
      }, 500);
    },
    
    // 前往商品详情
    goToProductDetail(id) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${id}`
      });
    }
  }
};
</script> 